// config/dynamicRoute.ts
import { getSystemInfo } from '@/services/main/index';
import { getAccessToken } from '@/access';

/**
 * 转换菜单为路由配置
 */
export function transformMenuToRoute(menu: any) {
    const route: any = {
      path: normalizePath(menu.path),
      name: menu.name,
      _tabMeta: {
        menuId: menu.menuId?.toString(),
        closable: menu.path !== 'home'
      }
    };
  
    if (menu.component) {
      route.component = normalizeComponentPath(menu.component);
    }
  
    if (menu.children?.length) {
      route.routes = menu.children.map(transformMenuToRoute);
    }
  
    return route;
  }
  
  function normalizePath(path: string): string {
    return `/${path.replace(/^\/|\/$/g, '')}`;
  }
  
  function normalizeComponentPath(component: string): string {
    return `@/pages/${component
      .replace(/^pages\//, '')
      .replace(/\/index$/, '')}`;
  }
  
  /**
   * 从缓存获取菜单数据
   */
  export function getCachedMenuData() {
    const cached = localStorage.getItem('menu-cache');
    if (!cached) return [];
    
    try {
      const { menuItems = [] } = JSON.parse(cached);
      return menuItems;
    } catch (e) {
      return [];
    }
  }